//---------------------------------------------------------------------
// Authors: jachymko
//
// Description: The Resize-Bitmap command.
//
// Creation Date: Dec 27, 2006
//
//---------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Management.Automation;

using Pscx.Commands.Internal;

namespace Pscx.Commands.Drawing
{
    [Cmdlet(PscxVerbs.Resize, PscxNouns.Bitmap)]
    [Description("Resizes bitmaps.")]
    public class ResizeBitmapCommand : PscxInputObjectPathCommandBase
    {
        private int _width;
        private int _height;

        [Parameter(Position = 1, Mandatory = true, HelpMessage = "The width of the resized bitmap.")]
        public int Width
        {
            get { return _width; }
            set { _width = value; }
        }

        [Parameter(Position = 2, Mandatory = true, HelpMessage = "The height of the resized bitmap.")]
        public int Height
        {
            get { return _height; }
            set { _height = value; }
        }

        protected override void BeginProcessing()
        {
            RegisterInputType<Bitmap>(ProcessBitmap);
            
            base.BeginProcessing();
        }

        protected override void ProcessPath(string path)
        {
            try
            {
                using(Bitmap bmp = new Bitmap(path))
                {
                    ProcessBitmap(bmp);
                }
            }
            catch(Exception exc)
            {
                WriteError(PscxErrorRecord.FileError(exc, path));
            }
        }

        private void ProcessBitmap(Bitmap bmp)
        {
            if(PixelFormatNotSupported(bmp.PixelFormat))
            {
                WriteError(PscxErrorRecord.PixelFormatError(bmp));
                return;
            }

            Bitmap output = new Bitmap(_width, _height, bmp.PixelFormat);

            using(Graphics gfx = Graphics.FromImage(output))
            {
                gfx.SmoothingMode = SmoothingMode.HighQuality;
                gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

                gfx.DrawImage(bmp, 0, 0, _width, _height);
            }
            
            WriteObject(output);
        }

        private bool PixelFormatNotSupported(PixelFormat pxf)
        {
            return (pxf == PixelFormat.Format1bppIndexed ||
                        pxf == PixelFormat.Format4bppIndexed ||
                        pxf == PixelFormat.Format8bppIndexed ||
                        pxf == PixelFormat.Format16bppArgb1555 ||
                        pxf == PixelFormat.Format16bppGrayScale ||
                        pxf == PixelFormat.Undefined ||
                        pxf == PixelFormat.DontCare);
        }
    }
}
